<template>
  <div>
    <el-menu
      :default-active="activeIndex"
      class="el-menu-demo"
      mode="horizontal"
      background-color="#00B4AD"
      text-color="#fff"
      active-text-color="#FFFFFF"
      @select="handleSelect"
    >
      <el-menu-item index="1"> <img src="@/assets/logo/icons8-social-network-64.png"> </el-menu-item>
      <el-menu-item index="2" @click="toHome">  基金业绩 </el-menu-item>
      <el-menu-item index="3" @click="toCopyright">  声明 </el-menu-item>
    </el-menu>
    <el-main>
      <el-row>
            <el-col v-loading="isLoading" :span="14" :offset="1">
              <div :id="id" :class="className" :style="{height:height,width:width}" />
            </el-col>
            <el-col :span="7" :offset="1">
              <el-select v-model="value" @change="onOptionsChange" placeholder="请选择时间">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
                <el-table
                  v-if="!isChatVisiable"
                  :data="fundTransactionList"
                  border
                  height="200"
                  style="width: 100%; margin-top:20px; margin-bottom:20px;"
                >
                <el-table-column
                  prop="date"
                  label="日期"
                  style="width: 100%"
                />
                <el-table-column
                  prop="daily_growth_rate"
                  label="增长率"
                  style="width: 100%"
                />
                <el-table-column
                  prop="positions"
                  label="策略推荐"
                  :formatter="positionsFormat"
                  style="width: 100%"
                />
              </el-table>

              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <el-button style="padding: 8px 1" type="info" @click="StartSyncData">启动</el-button>
                  <el-button style="padding: 8px 1" type="info" @click="StopSyncData">暂停</el-button>
                <!--
                  <el-button style="float: right; padding: 3px 0" type="text">清除</el-button>
                -->
                </div>
                <div v-for="o in messages" class="text item">
                  {{ o }}
                </div>
              </el-card>

            </el-col>
      </el-row>
      <el-row>
        <el-col v-loading="isLoading" :span="18" :offset="1">
        <!--
          <h3> 业绩历史数据 </h3>
            <el-table
              v-if="!isChatVisiable"
              :data="fundTransactionList"
              border
              style="width: 100%"
            >
            <el-table-column
              prop="date"
              label="日期"
              style="width: 100%"
            />
            <el-table-column
              prop="average_nav"
              label="平均净值"
              style="width: 100%"
            />
            <el-table-column
              prop="accumulated_net"
              label="累计净值"
              style="width: 100%"
            />
            <el-table-column
              prop="daily_growth_rate"
              label="增长率"
              style="width: 100%"
            />
            <el-table-column
              prop="subscription_status"
              label="状态"
              style="width: 100%"
            />
           <el-table-column
              prop="positions"
              label="算法推荐操作"
              :formatter="positionsFormat"
              style="width: 100%"
            />
          </el-table>
-->
        </el-col>
      </el-row>

    </el-main>
  </div>
</template>

<style>

</style>

<script>
import { GetConst, CurentTime } from '@/api/const'
import { fetchFundDetails, syncFundRecordData } from '@/api/fundrecord'
import echarts from 'echarts'
import resize from './mixins/resize'
import settings from '@/settings'
const axios = require('axios');

import Cookies from 'js-cookie'

export default {
  name: 'Learn',
  mixins: [resize],
  props: {
    terminal: {
      type: Object,
      default: {}
    },
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '600px'
    }
  },
  data() {
    return {
      count: 0,
      options: [{
        value: '30',
        label: '过去30天'
      }, {
        value: '60',
        label: '过去60天'
      }, {
        value: '90',
        label: '过去90天'
      }],
      value: '30',
      chart: null,
      driver: null,
      activeIndex: '2',
      startIndex: 0,
      endIndex: 0,
      pageItemNumbers: 0,
      shareUrl: '',
      isChatVisiable: false,
      user: 'Bob',
      comment: '',
      currentDate: new Date(),
      isCollapse: false,
      lecList: [],
      dateList: [],
      messages: [],
      timer: '',
      averageNavList: [],
      fundTransactionList: [],
      lecItemList: [],
      lecItemChatList: [],
      content: '',
      isLoading: false,
      allComment: '',
      lecItemID: '',
      outlineItemList: [],
      courseTitle: '',
      isLab: false,
      fund_id : '',
      isAdmin: false,
      screenWidth: document.body.clientWidth,
      showLoadMore: false
    }
  },
  watch: {
    screenWidth(val) {
      // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
      if (!this.timer) {
        // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
        this.screenWidth = val
        this.timer = true
        const that = this
        setTimeout(function() {
          // 打印screenWidth变化的值
          if (that.screenWidth < 1000) {
            that.isCollapse = true
          } else {
            that.isCollapse = false
          }
          that.timer = false
        }, 400)
      }
    }
  },
  created() {
    this.fund_cn_name =  Cookies.get('fund_cn_name')
    this.fund_id =  Cookies.get('fund_id')
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
    window.clearInterval(this.timer);
  },
  mounted() {
    const that = this
    window.onresize = () => {
      return (() => {
        window.screenWidth = document.body.clientWidth
        that.screenWidth = window.screenWidth
      })()
    }
    that.fund_id = Cookies.get('find_id')
    if (this.$route.params.id != null) {
      this.fund_id = this.$route.params.id
    }
    this.getFundList(this.$route.params.id)
    this.startIndex = 0
    this.pageItemNumbers = 8
    this.endIndex = this.startIndex + this.pageItemNumbers
  },
  methods: {
    hello(){ 
      console.log("Cycle Run Start!"); 
      let this_ = this
      axios.get(settings.baseURL + '/api/fundtransactionrecord-sync/' + this.$route.params.id + '/')
      .then(function (response) {
        console.log(response)
        var myDate = new Date();
        this_.messages.unshift(myDate.toLocaleString() + '-' + response.data)
        if(this_.messages.length > 5) {
          this_.messages.pop()
        }
        this_.getFundList(this_.$route.params.id)
      })
      .catch(function (error) {
        this_.isLoading = false
      })
    },
    StartSyncData(){
      this.messages.unshift("开始执行"); 
      this.timer = setInterval(this.hello, 20000);
    },
    StopSyncData(){
      this.messages.unshift("暂停执行"); 
      window.clearInterval(this.timer);
    },
    positionsFormat(row, column) {
      switch(row.positions) {
        case 0.0:
          return '无操作';
        case 1.0:
          return '买入';
        case -1.0:
          return '卖出';
        default:
          return '未知';
      }
    },
    getList(id) {
      this.isLoading = true
      fetchLecList(id).then(response => {
        this.lecList = response.output
        this.isLoading = false
      })
    },
    initChart() {
      this.chart = echarts.init(document.getElementById(this.id))
      const colors = ['#5470C6', '#EE6666']
      this.chart.setOption({
        color: colors,
        tooltip: {
          trigger: 'none',
          axisPointer: {
            type: 'cross'
          }
        },
        legend: {
          data: ['平均净值', '平均净值']
        },
        grid: {
          top: 70,
          bottom: 50
        },
        xAxis: [
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[1]
              }
            },
            axisPointer: {
              label: {
                // formatter: function (params) {
                //   return '降水量  ' + params.value + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                // }
              }
            },
            data: this.dateList
          },
          {
            type: 'category',
            axisTick: {
              alignWithLabel: true
            },
            axisLine: {
              onZero: false,
              lineStyle: {
                color: colors[0]
              }
            },
            axisPointer: {
              label: {
                // formatter: function (params) {
                //     return '降水量  ' + params.value
                //         + (params.seriesData.length ? '：' + params.seriesData[0].data : '');
                // }
              }
            },
            data: this.dateList
          }
        ],
        yAxis: [
          {
            type: 'value'
          }
        ],
        series: [
          {
            name: '平均净值',
            type: 'line',
            xAxisIndex: 1,
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.averageNavList
          },
          {
            name: '平均净值',
            type: 'line',
            smooth: true,
            emphasis: {
              focus: 'series'
            },
            data: this.averageNavList
          }
        ]
      })
    

      // this.chart.setOption({
      //   backgroundColor: '#FFFFFF',
      //   title: {
      //     top: 20,
      //     text: this.fund_cn_name + '-平均净值',
      //     textStyle: {
      //       fontWeight: 'normal',
      //       fontSize: 16,
      //       color: '#000000'
      //     },
      //     left: '10%'
      //   },
      //   tooltip: {
      //     trigger: 'axis',
      //     axisPointer: {
      //       lineStyle: {
      //         color: '#57617B'
      //       }
      //     }
      //   },
      //   legend: {
      //     top: 20,
      //     icon: 'rect',
      //     itemWidth: 14,
      //     itemHeight: 5,
      //     itemGap: 13,
      //     data: ['averageNav'],
      //     right: '4%',
      //     textStyle: {
      //       fontSize: 12,
      //       color: '#000000'
      //     }
      //   },
      //   grid: {
      //     top: 100,
      //     left: '2%',
      //     right: '2%',
      //     bottom: '2%',
      //     containLabel: true
      //   },
      //   xAxis: [{
      //     type: 'category',
      //     boundaryGap: false,
      //     axisLine: {
      //       lineStyle: {
      //         color: '#57617B'
      //       }
      //     },
      //     data: this.dateList
      //   }],
      //   yAxis: [{
      //     type: 'value',
      //     name: '',
      //     axisTick: {
      //       show: false
      //     },
      //     axisLine: {
      //       lineStyle: {
      //         color: '#57617B'
      //       }
      //     },
      //     axisLabel: {
      //       margin: 10,
      //       textStyle: {
      //         fontSize: 14
      //       }
      //     },
      //     splitLine: {
      //       lineStyle: {
      //         color: '#57617B'
      //       }
      //     }
      //   }],
      //   series: [{
      //     name: '平均净值',
      //     type: 'line',
      //     smooth: true,
      //     symbol: 'circle',
      //     symbolSize: 5,
      //     showSymbol: false,
      //     lineStyle: {
      //       normal: {
      //         width: 1
      //       }
      //     },
      //     areaStyle: {
      //       normal: {
      //         color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      //           offset: 0,
      //           color: 'rgba(137, 189, 27, 0.3)'
      //         }, {
      //           offset: 0.8,
      //           color: 'rgba(137, 189, 27, 0)'
      //         }], false),
      //         shadowColor: 'rgba(0, 0, 0, 0.1)',
      //         shadowBlur: 10
      //       }
      //     },
      //     itemStyle: {
      //       normal: {
      //         color: 'rgb(137,189,27)',
      //         borderColor: 'rgba(137,189,2,0.27)',
      //         borderWidth: 12

      //       }
      //     },
      //     data: this.averageNavList
      //   },
      //   // {
      //   //   name: 'CTCC',
      //   //   type: 'line',
      //   //   smooth: true,
      //   //   symbol: 'circle',
      //   //   symbolSize: 5,
      //   //   showSymbol: false,
      //   //   lineStyle: {
      //   //     normal: {
      //   //       width: 1
      //   //     }
      //   //   },
      //   //   areaStyle: {
      //   //     normal: {
      //   //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      //   //         offset: 0,
      //   //         color: 'rgba(0, 136, 212, 0.3)'
      //   //       }, {
      //   //         offset: 0.8,
      //   //         color: 'rgba(0, 136, 212, 0)'
      //   //       }], false),
      //   //       shadowColor: 'rgba(0, 0, 0, 0.1)',
      //   //       shadowBlur: 10
      //   //     }
      //   //   },
      //   //   itemStyle: {
      //   //     normal: {
      //   //       color: 'rgb(0,136,212)',
      //   //       borderColor: 'rgba(0,136,212,0.2)',
      //   //       borderWidth: 12

      //   //     }
      //   //   },
      //   //   data: [120, 110, 125, 145, 122, 165, 122, 220, 182, 191, 134, 150]
      //   // }, {
      //   //   name: 'CUCC',
      //   //   type: 'line',
      //   //   smooth: true,
      //   //   symbol: 'circle',
      //   //   symbolSize: 5,
      //   //   showSymbol: false,
      //   //   lineStyle: {
      //   //     normal: {
      //   //       width: 1
      //   //     }
      //   //   },
      //   //   areaStyle: {
      //   //     normal: {
      //   //       color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
      //   //         offset: 0,
      //   //         color: 'rgba(219, 50, 51, 0.3)'
      //   //       }, {
      //   //         offset: 0.8,
      //   //         color: 'rgba(219, 50, 51, 0)'
      //   //       }], false),
      //   //       shadowColor: 'rgba(0, 0, 0, 0.1)',
      //   //       shadowBlur: 10
      //   //     }
      //   //   },
      //   //   itemStyle: {
      //   //     normal: {
      //   //       color: 'rgb(219,50,51)',
      //   //       borderColor: 'rgba(219,50,51,0.2)',
      //   //       borderWidth: 12
      //   //     }
      //   //   },
      //   //   data: [220, 182, 125, 145, 122, 191, 134, 150, 120, 110, 165, 122]
      //   // }
      //   ]
      // })
    },
    getFundList(id) {
      // this.isLoading = true
      let this_ = this
      axios.get(settings.baseURL + '/api/transactionrecord-list/' + id + '/' + 30 + '/' + 1 + '/')
      .then(function (response) {
        var obj = JSON.parse(response.data)
        this_.fundTransactionList = obj.data
        this_.dateList = []
        this_.averageNavList = []
        for(var i = 0; i < this_.fundTransactionList.length; i++) {
          this_.dateList.unshift(this_.fundTransactionList[i].date)
          this_.averageNavList.unshift(this_.fundTransactionList[i].average_nav)
        }
        // this_.isLoading = false
        this_.initChart()
      })
      .catch(function (error) {
        console.log(error)
        this_.isLoading = false
      })
    },
    syncNewRecords() {
      this.isLoading = true
      syncFundRecordData(this.$route.params.id).then(response => {
          this.isLoading = false
          this.onOptionsChange()
      })
    },
    toCopyright() {
      this.$router.push({
        path: `/copyright`
      })
    },
    onOptionsChange() {
      let this_ = this
      axios.get(settings.baseURL + '/api/transactionrecord-list/' + this.$route.params.id + '/' + this.value + '/' + 1 + '/')
      .then(function (response) {
        var obj = JSON.parse(response.data)
        this_.fundTransactionList = obj.data
        this_.dateList = []
        this_.averageNavList = []
        for(var i = 0; i < this_.fundTransactionList.length; i++) {
          this_.dateList.unshift(this_.fundTransactionList[i].date)
          this_.averageNavList.unshift(this_.fundTransactionList[i].average_nav)
        }
        this_.initChart()
      })
      .catch(function (error) {
        this_.isLoading = false
      })
    },
    onSubmit() {
      if (this.comment === '') {
        this.$notify({
          title: 'Error',
          message: '请填入信息',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (this.comment.length >= 200) {
        this.$notify({
          title: 'Error',
          message: '评论信息太长, 请输入少于 200 个字符',
          type: 'error',
          duration: 2000
        })
        return
      }
      if (Cookies.get('UNAME') != null) {
        this.comment = '[' + CurentTime() + ']' + ' ' + Cookies.get('LOGIN') + ' ' + ':' + this.comment
      }
      addLecItemChat(this.lecItemID, this.comment).then(response => {
        this.lecItemChatList.unshift({ content: this.comment, lec_item_id: this.lecItemID })
      })
    },
    onCopy(e) {
      this.$message({
        message: '复制成功！快去粘贴给你的小伙伴吧',
        type: 'success'
      })
    },
    onError(e) {
      this.$message({
        message: '复制失败！',
        type: 'error'
      })
    },
    toHome() {
      this.$router.push({
        path: `/`
      })
    },
    handleOpen(key, keyPath) {
      this.lecItemList = []
      fetchLecItemList(key).then(response => {
        this.lecItemList = response.output
      })
    },
    handleClose(key, keyPath) {
      this.lecItemList = []
    },
    getLecItemDetail(lecID, itemID) {
      this.startIndex = 0
      this.pageItemNumbers = 8
      this.endIndex = this.startIndex + this.pageItemNumbers
      this.shareUrl = GetConst('BASE_URL') + 'learn/item/' + this.courseID + '/' + itemID
      this.lecItemID = itemID
      this.isChatVisiable = true
      this.isLoading = true
      fetchLecItemDetail(itemID).then(response => {
        this.content = response.output
      })
      fetchLecItemChatList(itemID, this.startIndex, this.endIndex).then(response => {
        if (response.output.length >= this.pageItemNumbers) {
          this.showLoadMore = true
        }
        this.lecItemChatList = response.output
        this.isLoading = false
      })
      fetchLecItemIsLab(itemID).then(response => {
      
      })
    },
    loadMore() {
      this.startIndex = this.endIndex + 1
      this.endIndex = this.endIndex + this.pageItemNumbers
      this.getLecItemChatList()
    },
    getLecItemChatList() {
      var _this = this
      _this.showLoadMore = false
      fetchLecItemChatList(this.lecItemID, this.startIndex, this.endIndex).then(response => {
        if (response.output.length >= _this.pageItemNumbers) {
          _this.showLoadMore = true
        }
        _this.lecItemChatList = _this.lecItemChatList.concat(response.output)
      })
    }
  }
}
</script>
